<template>
  <div id="login">
    <h3 style="text-align: center">登录系统</h3>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="isLoading">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  //TODO 登录失败将密码置空
  import login from "../../api/login";

  export default {
    name: "index",
    data() {
      const validateUser = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else {
          if (this.ruleForm.password !== '') {
            this.$refs.ruleForm.validateField('password');
          }
          callback();
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          callback();
        }
      };
      return {
        ruleForm: {
          username: '',
          password: ''
        },
        isLoading: false,
        rules: {
          username: [
            { validator: validateUser, trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm() {
        this.isLoading = true
        //获取token
        let v = this
        login.loginIn(this.ruleForm)
          .then(resp => {
            if (!resp.data){
              this.ruleForm.password = ''
              throw "err"
            }
            this.isLoading = false
            //将token 保存到Vuex中
            // console.log('后台传来的数据:' + resp.data.token)
            v.$store.commit('setToken',resp.data.token)
          })
          .then(() => {
            v.$router.replace({name: 'teacherList'})
            v.$message.success("登录成功")
          })
          .catch(err => {
            console.log(err)
            v.$message.error("用户名或密码错误")
            this.isLoading = false
          })
      },
      resetForm(formName) {
        this.isLoading = false
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>
  #login{
    width: 320px;
    margin: 200px auto;
    padding: 20px;
  }
</style>
